package drk.com.coincounter;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class CoinCounterActivity extends Activity  {
	private int mAppWidgetId;
private static String MY_AD_UNIT_ID = "a14e00a0b9e9e39";
	@Override
public void onStop()
{
	super.onStop();
	SharedPreferences settings = getSharedPreferences("CoinCountPref",0);
	SharedPreferences.Editor editor = settings.edit();
	
	int nCoins = this.getResources().getInteger(R.integer.nCoins);
	int[] curvalues = new int[nCoins];
	EditText et;
	for(int i = 0;i < nCoins;i++) {
		int id = 1000 * (i + 1);
		et = (EditText)findViewById(id + 2);
		curvalues[i] = parseInt(et.getText().toString());
	}

	for(int i = 0;i < nCoins;i++) {
		if(curvalues[i] == 0) {
			editor.putString(Integer.toString(i), "");
		} else {
			editor.putString(Integer.toString(i), Integer.toString(curvalues[i]));
		}
		
	}
    editor.commit();
}
	
		
	private Button[] btnsnumeric;
	OnClickListener myClickListener = new OnClickListener() {
		        @Override
		        public void onClick(View v) {
		        	Log.v("Coin","CLICKED" + v.getId());
		        	if((v.getId() & 7) == 1){
		        		// Minus button
		        		//Log.v("Coin","minus");
		        		EditText edittxt = (EditText)findViewById((v.getId()+1));
		            	int setme = checknum(edittxt) - 1;
		            	if(setme >= 0) {
		            		edittxt.setText(setme + "");
		            	}
		            	}
		            	else 
		            		if((v.getId() & 7) == 3) {
		            			// + button
		            		EditText edittxt2 = (EditText)findViewById((v.getId()-1)); // current id + 1 so *002
			            	int setme = checknum(edittxt2) + 1;
				            edittxt2.setText(setme + "");
		            	}
		        		
		        		
		        	}
		        	
		     
		        };
		    

		    private int checknum(EditText et) {
		    	try{
		    		int i = Integer.parseInt(et.getText().toString());
		    		
		    		return i;
		    	} catch(NumberFormatException e) {
		    		return 0;
		    		}
		    }
		    int privcnt = 1000;
		    
		    private TableRow makerow(int rownum)
		    {
		    	// Rowid is rownum + 1k
		    	// downbtn is rownum + 1k + 1;
		    	// edittext +2
		    	// upbtn + 3
		    	// label + 4
		    	int id = 1000 * (rownum + 1); // might break stuff using so row 0 is 1000 not 0;
	        	TableRow tr = new TableRow(this);
	        	tr.setId(id);
	        	tr.setLayoutParams(new LayoutParams(
	                    LayoutParams.FILL_PARENT,
	                    LayoutParams.WRAP_CONTENT)); 
	        	Button dwn = new Button(this);
	        	dwn.setOnClickListener(myClickListener);
	        	dwn.setId(id + 1);
	        	dwn.setText(R.string.btndown);
	        	tr.addView(dwn);
	        	
	        	EditText et = new EditText(this);
	        	et.setId(id + 2);
	        	et.setInputType(0x00001002);
	        	Log.v("Coin","EDITTEXT ID SET TO = " + (id+2));
	        	//et.setText("12");
	        	et.setWidth(80);
	        	tr.addView(et);
	        	
	        	Button up = new Button(this);
	        	up.setOnClickListener(myClickListener);
	        	up.setId(id + 3);
	        	up.setText(R.string.btnup);
	        	tr.addView(up);
	        	
	        	TextView t = new TextView(this);
	        	t.setText(coinnames[rownum]);
	        	t.setId(id + 4);
	        	tr.addView(t);
	        	//Log.v("Coin",rownum + "");
	        	return tr;
		    }
	String[] coinnames;
	int[] coinvalues;
		    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        final Context context = CoinCounterActivity.this;
        Resources res = getResources();
        coinnames = res.getStringArray(R.array.coinnames);
        coinvalues = res.getIntArray(R.array.coinvalues);
        
        //Log.d("Coin", context.getResources().getConfiguration().locale.getDisplayName());
        setResult(RESULT_CANCELED);	
        setContentView(R.layout.info);
        AdView adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);
        LinearLayout layout = (LinearLayout)findViewById(R.id.LinearLayout1);
        layout.addView(adView);
        adView.loadAd(new AdRequest());
        
        TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);
        int nCoins = res.getInteger(R.integer.nCoins);
        Log.v("Coin",nCoins +"");
        for(int i = 0; i < nCoins;i++) {
        	TableRow tr = makerow(i);
        	tl.addView(tr,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }
        // Capture our button from layout
              
        
        // Capture our button from layout
        Button button = (Button)findViewById(R.id.button1);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);

        Intent intent = getIntent();
		  Bundle extras = intent.getExtras();
		  Log.d("Coin","APP ID = " + extras.getInt(
	              AppWidgetManager.EXTRA_APPWIDGET_ID, 
	              AppWidgetManager.INVALID_APPWIDGET_ID));
		  if (extras != null) {
			  Log.d("Coin","Extras != null");
		      mAppWidgetId = extras.getInt(
		              AppWidgetManager.EXTRA_APPWIDGET_ID, 
		              AppWidgetManager.INVALID_APPWIDGET_ID);
		  }
		  if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			  Log.d("Coin","Invalid ID");
	            finish();
	        }
	        SharedPreferences settings = getSharedPreferences("CoinCountPref",0);
	        try {
	        	int id;
	        	EditText et;
	        	for(int i = 0; i < nCoins;i++) {
	        		id = ((i+1) * 1000) + 2;
	        		et = (EditText)findViewById(id);
	        		et.setText(settings.getString("" + i, ""));
	        	}
	            	            
	        } catch(NullPointerException e) { Log.d("Coin", e.toString());}

    }
	
	private int parseInt(String s) {
		int i = 0;
		try{ i = Integer.parseInt(s); }
		catch(NumberFormatException e) { Log.d("Coin", "Handled!with a zero " + e.toString());}
		return i;
	}
	private String GetTotal()
	{
		int nCoins = this.getResources().getInteger(R.integer.nCoins);
		int[] curvalues = new int[nCoins];
		EditText et;
		for(int i = 0;i < nCoins;i++) {
			int id = 1000 * (i + 1);
			et = (EditText)findViewById(id + 2);
			curvalues[i] = parseInt(et.getText().toString());
		}
		int Total = 0;
		for(int i = 0;i < nCoins;i++) {
			Total = Total + (curvalues[i] * coinvalues[i]);
		}
		float dectotal = (float)Total / 100;
		Log.d("Coin", "returning " + Float.toString(dectotal));
		if(dectotal > 0) {
			return this.getResources().getString(R.string.symbol) + Float.toString(dectotal);
		} else {
			return this.getResources().getString(R.string.symbol) + "0";
		}
		
	}
	
	private OnClickListener mCorkyListener = new OnClickListener() {
	  @Override
		public void onClick(View arg0) {
		  final Context context = CoinCounterActivity.this;

          // When the button is clicked, save the string in our prefs and return that they
          // clicked OK.
          String titlePrefix = GetTotal();//mAppWidgetPrefix.getText().toString();
          //saveTitlePref(context, mAppWidgetId, titlePrefix);

          // Push widget update to surface with newly set prefix
          AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
          CoinCounterWidget.updateAppWidget(context, appWidgetManager,
                  mAppWidgetId, titlePrefix);

          // Make sure we pass back the original appWidgetId
          Intent resultValue = new Intent();
          resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
          setResult(RESULT_OK, resultValue);
          
       
        
          finish();
		  
			// TODO Auto-generated method stub
			
		}
	};
	
	


	
	
	
}
